// 日期格式化
const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

// 数字格式化（补零）
const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

// 价格格式化 - 显示人民币符号和精确到小数点后两位
const formatPrice = price => {
    if (typeof price !== 'number') {
        return '¥0.00';
    }
    return '¥' + price.toFixed(2);
}

// 评分格式化 - 保留一位小数
const formatRating = rating => {
    if (typeof rating !== 'number') {
        return '0.0';
    }
    return rating.toFixed(1);
}

// 简化地址显示
const formatAddress = address => {
    if (!address) return '';

    // 如果地址太长，只显示前20个字符
    if (address.length > 20) {
        return address.substring(0, 20) + '...';
    }
    return address;
}

// 检查是否为空
const isEmpty = value => {
    if (value === null || value === undefined) {
        return true;
    }
    if (typeof value === 'string' && value.trim() === '') {
        return true;
    }
    if (Array.isArray(value) && value.length === 0) {
        return true;
    }
    if (typeof value === 'object' && Object.keys(value).length === 0) {
        return true;
    }
    return false;
}

// 节流函数 - 防止频繁触发事件
const throttle = (fn, delay = 500) => {
    let timer = null;
    let lastTime = 0;

    return function (...args) {
        const now = Date.now();
        const remaining = delay - (now - lastTime);

        if (remaining <= 0) {
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }

            lastTime = now;
            fn.apply(this, args);
        } else if (!timer) {
            timer = setTimeout(() => {
                lastTime = Date.now();
                timer = null;
                fn.apply(this, args);
            }, remaining);
        }
    };
}

// 防抖函数 - 防止频繁触发事件
const debounce = (fn, delay = 500) => {
    let timer = null;

    return function (...args) {
        if (timer) {
            clearTimeout(timer);
        }

        timer = setTimeout(() => {
            fn.apply(this, args);
            timer = null;
        }, delay);
    };
}

// 随机颜色生成
const randomColor = () => {
    return '#' + Math.floor(Math.random() * 16777215).toString(16);
}

// 将评分转换为星星显示
const ratingToStars = (rating) => {
    const fullStars = Math.floor(rating);
    const halfStar = rating - fullStars >= 0.5;
    const emptyStars = 5 - fullStars - (halfStar ? 1 : 0);

    return {
        full: fullStars,
        half: halfStar ? 1 : 0,
        empty: emptyStars
    };
}

module.exports = {
    formatTime,
    formatNumber,
    formatPrice,
    formatRating,
    formatAddress,
    isEmpty,
    throttle,
    debounce,
    randomColor,
    ratingToStars
} 